package com.kuaizu.es.buis.imp;

import cn.hutool.json.JSONUtil;
import com.kuaizu.es.buis.IProjectBusinessServiceImpl;
import com.kuaizu.es.config.MQConfig;
import com.kuaizu.es.mapper.EsProjectMapper;
import com.kuaizu.es.pojo.PageData;
import kuaizu.common.mqconst.MQConstant;
import kuaizu.common.tablepojo.Project;
import kuaizu.common.vo.ProjectVO;
import com.kuaizu.es.pojo.doc.ProjectDoc;
import com.kuaizu.es.pojo.dto.ProjectDTO;
import com.kuaizu.es.pojo.pram.QueryDataPoJectInfoPram;
import com.kuaizu.es.utils.EsUtil;
import kuaizu.common.esindex.EsIndexConst;
import jakarta.annotation.Resource;
import kuaizu.common.exception.MassageException;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: wangmx15
 * @date: 2025/8/23
 **/
@Component
@Log4j2
public class ProjectBusinessService implements IProjectBusinessServiceImpl {
    @Resource
    private EsProjectMapper esProjectMapper;
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient esClient;
    @Resource
    private EsUtil esUtil;

    //初始化es
    @Override
    public void initEs() {
        log.info("---初始化es---");
        addData(getAllProject());
        log.info("---初始化创建索引成功---");
    }

    //获取全部的项目信息
    @Override
    public List<ProjectDTO> getAllProject() {
        log.info("---获取全部的项目信息---");
        return esProjectMapper.getAllProject();


    }

    //创建索引
    @Override
    public void createIndex() {
        log.info("---初始化创建索引---");
        esUtil.createProjectIndex();

    }

    //批量添加数据
    @Override
    public void addData(List<ProjectDTO> list) {
        log.info("---添加数据---");
        //往es中添加数据
        BulkRequest request = new BulkRequest(EsIndexConst.PROJECT_INDEX);
        //将list中的dto转换成ProjectDoc
        List<ProjectDoc> docs = new ArrayList<>();
        for (ProjectDTO dto : list) {
            ProjectDoc doc = new ProjectDoc();
            BeanUtils.copyProperties(dto, doc);
            // 2.2.创建新增文档的Request对象
            request.add(new IndexRequest()
                    .id(doc.getId().toString())
                    .source(JSONUtil.toJsonStr(doc), XContentType.JSON));
        }
        try {
            esClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new MassageException("添加数据失败");
        }
    }

    //查询数据
    @Override
    public PageData<ProjectVO> queryDatapPojectInfo(QueryDataPoJectInfoPram req) {
        return send(req, "projectInfo");
    }

    //添加数据
    @Override
    public void addData(Project project) {
        ProjectDoc doc = new ProjectDoc();
        //根据对应信息查询学校和专业
        doc =  esProjectMapper.getSchoolAndMajor(project);
        BeanUtils.copyProperties(project, doc);
        //将dto转成
        //将doc对象添加到es中
        IndexRequest req = new IndexRequest(EsIndexConst.PROJECT_INDEX).id(doc.getId().toString());
        req.source(JSONUtil.toJsonStr(doc),XContentType.JSON);
        try {
            esClient.index(req, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new MassageException("添加失败");
        }
        log.info("---添加成功---");
    }

    //批量添加数据
    @Override
    public void addDataBatch() {

    }

    @Override
    public void deleteProject(Integer id) {
        //删除项目
        // 1.准备Request，两个参数，第一个是索引库名，第二个是文档id
        DeleteRequest request = new DeleteRequest(EsIndexConst.PROJECT_INDEX, id.toString());
        // 2.发送请求
        try {
            esClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new MassageException("删除项目");
        }
        log.info("---删除项目成功---");
    }

    @Override
    public PageData<ProjectVO> queryProjectBySkillDetails(QueryDataPoJectInfoPram req) {
        return send(req, "skillDetails");
    }

    public PageData<ProjectVO> send(QueryDataPoJectInfoPram req, String name) {
        SearchRequest searchRequest = new SearchRequest(EsIndexConst.PROJECT_INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        int from = (req.getPageNum() - 1) * req.getPageSize(); // 页码从1开始时
        sourceBuilder.from(from); // 起始页码（0 开始）
        sourceBuilder.size(req.getPageSize()); // 每页条数
        if (!(null != req.getStr())) {
            //为空查询全部
            sourceBuilder.query(QueryBuilders.matchAllQuery());
        } else {
            sourceBuilder.query(QueryBuilders.matchQuery(name, req.getStr())
                    .fuzziness(Fuzziness.AUTO) // 自动模糊匹配
                    .prefixLength(2)); // 前缀长度
            // 前缀关键词
        }
        searchRequest.source(sourceBuilder);
        SearchResponse response = null;
        try {
            response = esClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new MassageException("查询文档失败");
        }
        System.out.println("匹配到的文档数：" + response.getHits().getTotalHits().value);
        //将查询的数据转成对应ListProjectVo对象
        PageData<ProjectVO> page = esUtil.returnDatatShift(response, new ProjectVO());
        page.setPageSize(req.getPageSize());
        page.setPageNum(req.getPageNum());
        return page;
    }

}
